<?php

namespace App\Service\PayApi\Callback;

use App\Model\Dao\MchInfoDao;
use App\Model\Dao\TradeOrderBaseDao;
use App\Model\Dao\TradeOrderDetailDao;
use App\Model\Enum\OrderTransStatusEnum;
use App\Model\Enum\TradeTrans\TradeTransSettleStatusEnum;
use App\Utils\CustomUtils;
use App\Utils\RedisUtils;
use App\Utils\SignUtils;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Redis\Redis;
use Hyperf\Utils\Arr;
use Hyperf\Utils\Coroutine;
use Swlib\SaberGM;

/**
 * Class PayCallbackService
 * 商户API支付回调 
 */
class PayCallbackService {

    const MERCHANT_NOTIFY_RETRY_INTERVAL = [
        0 => 0,
        1 => 5,
        2 => 10,
        3 => 30,
        4 => 90,
        5 => 300,
    ];

    /**
     * @var TradeOrderDetailDao
     * @Inject()
     */
    protected $TradeOrderDetailDao;

    /**
     * @var TradeOrderBaseDao
     * @Inject()
     */
    protected $TradeOrderBaseDao;

    /**
     * @var MchPayCallbackNotifyService
     * @Inject()
     */
    protected $MchPayCallbackNotifyService;

    /**
     * 处理网关支付回调
     *
     * @param $param
     *
     * @return array
     * @throws \Exception
     */
    public function handle ($param) {

        // 订单查询
        $order = $this->_getOrder($param);

        // 验签
        $this->_verifySign($order);

        // 处理订单
        $this->_handleOrder($order, $param);

        // 发送邮件通知
        $this->_sendMail();

        // 发送商户回调
        $this->MchPayCallbackNotifyService->pushIntoNotifyQueue($order['orderDetail'], $order['orderBase']);

        return CustomUtils::buildSuccess();
    }

    /**
     * 验签 todo
     *
     * @param $order
     */
    protected function _verifySign ($order) {

        $orderDetail = $order['orderDetail'];

        $isSignValid = false;

        if ($orderDetail['isTest'] == 1) {
            $isSignValid = true;
        }
        else {
            $isSignValid = true;
        }

    }

    /**
     * 获取订单详情
     *
     * @param $param
     *
     * @return array
     * @throws \Exception
     */
    protected function _getOrder ($param) {

        $orderDetail = $this->TradeOrderDetailDao->getWhere(['relNo' => $param['relNo']]);

        if (!$orderDetail) {
            throw new \Exception('未找到订单详情');
        }

        $orderBase = $this->TradeOrderBaseDao->getWhere(['orderId' => $orderDetail['id']]);

        if (!$orderDetail) {
            throw new \Exception('未找到订单详情');
        }

        $order = [
            'orderDetail' => $orderDetail,
            'orderBase'   => $orderBase,
        ];

        return $order;
    }

    /**
     * 处理订单状态
     *
     * @param $order
     * @param $param
     */
    protected function _handleOrder ($order, $param) {

        $orderId = $order['orderDetail']['id'];

        $update = [
            'transStatus' => OrderTransStatusEnum::BANK_CALLBACK_SUCCESS,
        ];

        $this->TradeOrderDetailDao->update($orderId, $update);
    }

    /**
     * 发送邮件 todo
     */
    protected function _sendMail () {

    }
}
